﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using AllInOnePluginBL.Helpers;
using Newtonsoft.Json;

namespace AllInOnePluginBL.FileHostingExtractors
{
    /// <summary>
    /// Summary description for VideozerExtractor
    /// </summary>
    public class VideozerExtractor : IFileHostingExtractor
    {
        private const string CONTROL_URI = "http://www.videozer.com/player_control/settings.php?v={0}";
        private const string URL_REGEX = @"http://www.videozer.com/embed/([A-Za-z0-9]+)";
        private const string MOVIE_URL = "http://www.videozer.com/embed/";
        private const string TOKEN = "\"token1\":\"(.+?)\"";

        public List<string> GetMovieUrls(string content)
        {
            var movieUrls = new List<string>();
            var exp = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            var matches = exp.Matches(content);
            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    var movieUrl = match.Value;
                    if (!movieUrls.Contains(movieUrl))
                    {
                        movieUrls.Add(movieUrl);
                    }
                }
            }
            return movieUrls;
        }

        public VideoResult ExtractMovieUrl(string movieUrl)
        {
            var movieCode = movieUrl.Substring(movieUrl.Length - 8);
            //var content = Utils.GetPage(string.Format(CONTROL_URI, movieCode), Encoding.Default, "http://www.videozer.com", string.Empty);

            var content = File.ReadAllText(@"d:\json.txt");

            var output = JsonConvert.DeserializeObject(content) as Newtonsoft.Json.Linq.JObject;
            if (output == null) throw new Exception("Failed to load config data");

            const int KEY_2 = 215678;
            var msg = output["cfg"]["msg"];
            var token = Convert.FromBase64String(output["cfg"]["environment"]["token1"].ToString());
            var cypher = output["cfg"]["info"]["sece2"].ToString();
            var key1 = int.Parse(output["cfg"]["environment"]["rkts"].ToString());



            var errorMatch = Regex.Match(content, "\"display\":{\"text\":\"(.+?)\"", RegexOptions.Singleline);
            if (errorMatch.Success)
            {
                throw new Exception(errorMatch.Groups[1].Value);
            }

            var match = Regex.Match(content, TOKEN, RegexOptions.IgnoreCase);
            if (!match.Success)
            {
                throw new Exception("Cant find videozer token");
            }

            var convertedBytes = Convert.FromBase64String(match.Groups[1].Value.Replace("\\", string.Empty));

            const string videoTitleRegEx = "\"video\":{\"title\":\"(.+?)\"";
            match = Regex.Match(content, videoTitleRegEx, RegexOptions.IgnoreCase);
            return match.Success ?
                new VideoResult(Encoding.UTF8.GetString(convertedBytes), match.Groups[1].Value, true) :
                new VideoResult(Encoding.UTF8.GetString(convertedBytes), true);
        }

        public bool IsContainVideoLink(string content)
        {
            var match = Regex.Match(content, URL_REGEX, RegexOptions.IgnoreCase);
            return match.Success;
        }

        //return result in specified length
        public string hex2Bin(string strHex, int bit)
        {
            int decNumber = hex2Dec(strHex);
            return dec2Bin(decNumber).PadLeft(bit, '0');
        }

        //return result in specified length
        public string dec2Bin(int val, int bit)
        {
            return Convert.ToString(val, 2).PadLeft(bit, '0');
        }

        public string hex2Bin(string strHex)
        {
            int decNumber = hex2Dec(strHex);
            return dec2Bin(decNumber);
        }

        public string bin2Hex(string strBin)
        {
            int decNumber = bin2Dec(strBin);
            return dec2Hex(decNumber);
        }

        private string dec2Hex(int val)
        {
            return val.ToString("X");
            //return Convert.ToString(val,16);
        }

        private int hex2Dec(string strHex)
        {
            return Convert.ToInt16(strHex, 16);
        }

        private string dec2Bin(int val)
        {
            return Convert.ToString(val, 2);
        }

        public int bin2Dec(string strBin)
        {
            return Convert.ToInt16(strBin, 2);
        }
    }
}